package net.neptech.websocket;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.PostConstruct;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import net.neptech.config.SpringContextUtil;
import net.neptech.entity.vo.dto.KSignalMessage;
import net.neptech.service.ars.RealTimeASRService;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/ws/audio/{conferenceId}/{userId}/{userName}")
public class AudioWebSocketHandler {

    private static RealTimeASRService asrService;
    private static KafkaTemplate<String, String> kafkaTemplate;

    private Session session;
    private String conferenceId;
    private String userId;
    private String userName;

    private static final ConcurrentHashMap<String, Boolean> transcriptionStartedMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        asrService = SpringContextUtil.getBean(RealTimeASRService.class);
        kafkaTemplate = SpringContextUtil.getBean(KafkaTemplate.class);
    }

    @OnOpen
    public void onOpen(@PathParam("conferenceId") String conferenceId,
                       @PathParam("userId") String userId,
                       @PathParam("userName") String userName,
                       Session session) {
//      本来就是前端页面的pinia store，这里直接写死，测试用，现在和整体项目没连接上
        this.conferenceId = conferenceId;
        this.userId = userId;
        this.userName = userName;
        this.session = session;
        if ("1".equals(userId)){
            userName="用户1";
        } else if ("2".equals(userId)) {
            userName="用户2";
        } else if ("3".equals(userId)) {
            userName="用户3";
        }
        log.info("🎙️ 音频流连接建立: {} | userId={} | userName={}", conferenceId, userId, userName);
    }

    @OnMessage
    public void onMessage(byte[] audioData,
                          @PathParam("conferenceId") String conferenceId) {
        try {
            // ✅ 按“会议:用户”维度启动/写入
            String asrKey = conferenceId + ":" + userId;
            transcriptionStartedMap.computeIfAbsent(asrKey, key -> {
                if("1".equals(userId)){
                    userName="用户1";
                }else if ("2".equals(userId)){
                    userName="用户2";
                }else if ("3".equals(userId)){
                    userName="用户3";
                }
                asrService.startTranscription(asrKey, userName); // 传入“说话者名字”
                log.info("🟢 实时语音识别启动成功: {}", asrKey);
                return true;
            });
            asrService.sendAudioData(asrKey, audioData);

        } catch (Exception e) {
            log.error("❌ 音频处理失败: {}", e.getMessage(), e);
        }
    }

    @OnClose
    public void onClose(@PathParam("conferenceId") String conferenceId,
                        @PathParam("userId") String userId) {
        log.info("⏹️ 音频流断开: {} | userId={}", conferenceId, userId);
        String asrKey = conferenceId + ":" + userId;
        asrService.stopTranscription(asrKey);
        transcriptionStartedMap.remove(asrKey);
        // TODO: 可以做优化：最后一个人离开时才 stop，但是现在就是先随便坐，后期再更改，对接不上整体项目
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket 音频传输错误", throwable);
    }

    private void sendSubtitleToKafka(String conferenceId, String fromUserId, String fromUserName, String text) {
        try {
            KSignalMessage kMsg = new KSignalMessage();
            kMsg.setConferenceId(conferenceId);
            kMsg.setFromUserId(fromUserId);
            kMsg.setType("speech-text");
            kMsg.setData(new SubtitleMessage(fromUserId, fromUserName, text));

            kafkaTemplate.send("lxy-signaling-top", JSON.toJSONString(kMsg));
            log.info("📝 已投递字幕到 Kafka: {} | {}: {}", conferenceId, fromUserName, text);

        } catch (Exception e) {
            log.error("❌ 投递字幕失败", e);
        }
    }

    public static class SubtitleMessage {
        public String fromUserId;
        public String fromUserName;
        public String text;

        public SubtitleMessage(String fromUserId, String fromUserName, String text) {
            this.fromUserId = fromUserId;
            this.fromUserName = fromUserName;
            this.text = text;
        }
    }
}
